package com.test.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.Map;

@Configuration
@AutoConfigureBefore({DynamicDataSourceAutoConfiguration.class})
@EnableConfigurationProperties
public class DynamicDataSourceConfig {

    @Bean
    @Primary
    public DataSource dataSource(DynamicDataSourceProvider dynamicDataSourceProvider) {
        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        dataSource.setPrimary("master");
        dataSource.setStrict(false);
        
        // 使用 addDataSource 方法添加数据源
        Map<String, DataSource> dataSourceMap = dynamicDataSourceProvider.loadDataSources();
        for (Map.Entry<String, DataSource> entry : dataSourceMap.entrySet()) {
            dataSource.addDataSource(entry.getKey(), entry.getValue());
        }
        
        return dataSource;
    }

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        return new AbstractDataSourceProvider() {
            @Override
            public Map<String, DataSource> loadDataSources() {
                Map<String, DataSourceProperty> dataSourcePropertiesMap = new java.util.HashMap<>();
                // 主数据源
                DataSourceProperty masterProperty = new DataSourceProperty();
                masterProperty.setUrl("jdbc:mysql://localhost:3306/master_db?useUnicode=true&characterEncoding=utf8&useSSL=false");
                masterProperty.setUsername("root");
                masterProperty.setPassword("123");
                masterProperty.setDriverClassName("com.mysql.cj.jdbc.Driver");
                dataSourcePropertiesMap.put("master", masterProperty);
                
                return createDataSourceMap(dataSourcePropertiesMap);
            }
        };
    }
} 